package Numpy;

public class SpiralMatrix59 {
    public static void main(String[] args) {
        System.out.println(generateMatrix1(4).toString());
    }

    public static int[][] generateMatrix1(int n) {
        int[][] result = new int[n][n];
        int loop = 0;
        int start = 0;
        int count = 1;
        int i = 0;
        int j = 0;

        while (loop++ < n / 2) {
            //第一行，从左往右
            for (j = start; j < n - loop; j++) {
                result[start][j] = count++;
            }
            // 最后一列，从上往下
            for (i = start; i < n - loop; i++) {
                result[i][j] = count++;
            }
            // 最后一行，从右向左
            for (; j >= loop; j--) {
                result[i][j] = count++;
            }
            // 第一行，从下往上
            for (; i >= loop; i--) {
                result[i][j] = count++;
            }

            start++;
        }

        while (n % 2 == 1) {
            result[start][start] = count;
        }

        return result;
    }

    public static int[][] generateMatrix2(int n) {
        int[][] result = new int[n][n];
        if (n == 1) {
            result[0][0] = 1;
            return result;
        }
        int up = 0, down = n - 1, left = 0, right = n - 1;
        int index = 1;
        while (index <= n * n) {
            for (int i = left; i <= right; i++) {
                result[up][i] = index++;
            }
            up++;
            for (int i = up; i <= down; i++) {
                result[i][right] = index++;
            }
            right--;
            for (int i = right; i >= left; i--) {
                result[down][i] = index++;
            }
            down--;
            for (int i = down; i >= up; i--) {
                result[i][left] = index++;
            }
            left++;
        }

        return result;
    }

}
